package com.oscar.ehome.provider.zxing.client.android.camera.open;

import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

import com.oscar.ehome.App;
import com.oscar.ehome.provider.zxing.client.android.camera.CameraManager;
import com.oscar.ehome.provider.zxing.client.android.camera.IActivityLifiCycle;
import com.oscar.ehome.provider.zxing.client.android.camera.SensorControler;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.view.loginview.CaptureActivity;


/**
 * 正方形的CamerContainer
 */
public class SquareCameraContainer extends FrameLayout implements IActivityLifiCycle {
    public static final String TAG = "SquareCameraContainer";

    private Context mContext;

    private CaptureActivity mActivity;

    private boolean mFocusSoundPrepared;

    private int mFocusSoundId;

    private String mImagePath;

    private SensorControler mSensorControler;

    private CameraManager cameraManager;

    public static final int RESETMASK_DELY = 1000; //一段时间后遮罩层一定要隐藏

    public SquareCameraContainer(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public SquareCameraContainer(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    void init() {
        mSensorControler = SensorControler.getInstance();
        cameraManager = new CameraManager(mContext);

        mSensorControler.setCameraFocusListener(new SensorControler.CameraFocusListener() {
            @Override
            public void onFocus() {
                int screenWidth = App.mScreenWidth;
                Point point = new Point(screenWidth / 2, screenWidth / 2);
                onCameraFocus(point);
            }
        });
    }

    public void bindActivity(CaptureActivity activity) {
        this.mActivity = activity;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int len = App.mScreenWidth;
        //保证View是正方形
        setMeasuredDimension(len, len);
    }

    /**
     * 记录是拖拉照片模式还是放大缩小照片模式
     */

    private static final int MODE_INIT = 0;
    /**
     * 放大缩小照片模式
     */
    private static final int MODE_ZOOM = 1;
    private int mode = MODE_INIT;// 初始状态

    private float startDis;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
/** 通过与运算保留最后八位 MotionEvent.ACTION_MASK = 255 */
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            // 手指压下屏幕
            case MotionEvent.ACTION_DOWN:
                mode = MODE_INIT;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mode = MODE_ZOOM;
                /** 计算两个手指间的距离 */
                startDis = spacing(event);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == MODE_ZOOM) {
                    //只有同时触屏两个点的时候才执行
                    if (event.getPointerCount() < 2) return true;
                    float endDis = spacing(event);// 结束距离
                    //每变化10f zoom变1
                    int scale = (int) ((endDis - startDis) / 10f);
                    if (scale >= 1 || scale <= -1) {
                        //将最后一次的距离设为当前距离
                        startDis = endDis;
                    }
                }
                break;
            // 手指离开屏幕
            case MotionEvent.ACTION_UP:
                if (mode != MODE_ZOOM) {
                    //设置聚焦
                    Point point = new Point((int) event.getX(), (int) event.getY());
                    onCameraFocus(point);
                } else {
                }
                break;
        }
        return true;
    }

    /**
     * 两点的距离
     */
    private float spacing(MotionEvent event) {
        if (event == null) {
            return 0;
        }
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 相机对焦  默认不需要延时
     *
     * @param point
     */
    private void onCameraFocus(final Point point) {

        onCameraFocus(point, false);
    }

    /**
     * 相机对焦
     *
     * @param point
     * @param needDelay 是否需要延时
     */
    public void onCameraFocus(final Point point, boolean needDelay) {
        long delayDuration = needDelay ? 3 : 0;

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!mSensorControler.isFocusLocked()) {
                        if (!CommonUtils.isFirst) {
                            CommonUtils.idcard = 1;
                        }
                    if (cameraManager.onFocus(point, autoFocusCallback)) {
                        mSensorControler.lockFocus();
                    }
                }
            }
        }, delayDuration);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

    private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            //聚焦之后根据结果修改图片
            if (success) {
                mHandler.removeCallbacks(null, null);
            } else {
                //聚焦失败显示的图片，由于未找到合适的资源，这里仍显示同一张图片
                mHandler.removeCallbacks(null, null);
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //一秒之后才能再次对焦
                    mSensorControler.unlockFocus();
                }
            }, 1000);
        }
    };

    @Override
    public void onStart() {
        mSensorControler.onStart();
    }

    @Override
    public void onStop() {
        mSensorControler.onStop();
    }
}
